package com.cicada.cocos2dsamples.samples;

import java.util.Random;

import org.cocos2d.actions.base.CCRepeatForever;
import org.cocos2d.actions.instant.CCCallFuncN;
import org.cocos2d.actions.interval.CCAnimate;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.nodes.CCAnimation;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteFrameCache;
import org.cocos2d.nodes.CCSpriteSheet;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;

public class AnimationWithPlist extends BaseActivity {

	@Override
	public CCLayer getLayer() {
		return new Layer();
	}

	static class Layer extends CCLayer {
		public CGSize winSize = CCDirector.sharedDirector().winSize();
		CCAnimate animate_idle;
		CCAnimate animate_walking;

		public Layer() {
			initHeroAnimation();
			schedule("heros", 0.1f);
		}

		public void heros(float dt) {
			createHero();
		}

		public void createHero() {
			CCSprite hero = CCSprite.sprite(animate_idle.getAnimation()
					.frames().get(0));

			float posY = new Random().nextInt((int) (winSize.getHeight() - hero
					.getContentSize().height))
					+ (hero.getContentSize().height / 2);
			hero.setPosition(hero.getContentSize().width / 2, posY);
			addChild(hero);

			CCMoveTo moveto = CCMoveTo.action(
					3.0f,
					CGPoint.ccp(winSize.getWidth()
							- hero.getContentSize().width / 2, posY));
			CCSequence sequence = CCSequence.actions(moveto,
					CCCallFuncN.action(this, "heroFinished"));
			CCAnimate animate = animate_walking.copy();
			hero.runAction(CCRepeatForever.action(animate));
			hero.runAction(sequence);
		}

		public void heroFinished(Object node) {
			((CCSprite) node).removeSelf();
		}

		public void initHeroAnimation() {
			CCSpriteFrameCache cache = CCSpriteFrameCache
					.sharedSpriteFrameCache();
			cache.addSpriteFrames("deadknight.plist");
			CCSpriteSheet.spriteSheet("deadknight.png");

			CCAnimation animation_idle = CCAnimation.animation("idle", 0.1f);
			CCAnimation animation_walking = CCAnimation.animation("walking",
					0.05f);

			for (int i = 0; i < 12; i++) {
				if (i < 5) {
					animation_idle.addFrame(cache.getSpriteFrame(String.format(
							"deadknightidle_%04d.png", i + 1)));
				}

				if (i < 12) {
					animation_walking.addFrame(cache.getSpriteFrame(String
							.format("deadknightwalk_%04d.png", i + 1)));
				}
			}

			animate_idle = CCAnimate.action(animation_idle);
			animate_walking = CCAnimate.action(animation_walking);
		}
	}
}
